import {
	HTTP_STATUS,
	HTTP_STATUS_CODE
} from '@/const/status'
import {
	base
} from './config'
import {
	logError,
	showToast,
	showModal
} from '@/utils'
import {permisAuth} from '@/utils/permis.js'
import store from '@/store/index.js'

const redirectToLogin = (type) => {
	uni.removeStorageSync('token')
	uni.removeStorageSync('refreshToken')
	uni.removeStorageSync('tokenType')
	store.commit('setToken','')
	// type !== HTTP_STATUS.FORBIDDEN && showToast('登录失效，请重新登录')
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let currentPage = '/' + routes[routes.length - 1].route;
	let currentParam = routes[routes.length - 1].options; //获取路由参数
	let param = ''
	Object.keys(currentParam).forEach((key, index) => {
		param += ((index == 0 ? '?' : '&') + key + '=' + currentParam[key])
	})
	store.state.showModalReady && showModal({
		title: '提示',
		confirmText: '去登录',
		content: '您还未登录'
	}).then(() => {
		console.log('then')
		setTimeout(() => {
			uni.reLaunch({
				url: `/pages/account/pages/login${currentPage=='pages/account/pages/login'?'':('?backUrl='+encodeURIComponent(currentPage+param))}`
			})
		}, 1500)
	})
}

const checkTokenExpire = () => {
	let expires_at = uni.getStorageSync('expires_at')
	if (new Date().getTime() > expires_at - 60 * 1000) {
		return false
	}
	return true
}

export default {
	baseOptions(params, method = 'GET') {
		return new Promise((resolve, reject) => {
			let {
				url,
				data,
				otherOptions = {
					noToast: false,
					noCheck: false,
				}
			} = params
			let token = uni.getStorageSync('token')
			let refreshToken = uni.getStorageSync('refreshToken')
			let tokenType = uni.getStorageSync('tokenType')
			// if (!checkTokenExpire() && !otherOptions.refresh && refreshToken) {
			//   this.refreshToken()
			// }
			// if (!token && !otherOptions.noNeedToken) redirectToLogin()
			let contentType = method == 'GET' ? 'application/x-www-form-urlencoded' : 'application/json'
			contentType = params.contentType || contentType
			const header = otherOptions.noHeaders ? {
				'content-type': contentType,
			} : {
				'content-type': contentType,
				'CLIENT-TOC': 'Y',
				'Tenant-Id':  uni.getStorageSync("tenantId"),
				Authorization: `${otherOptions.isLogin?'Basic c29jaWFsOnNvY2lhbA==':
          otherOptions.refresh ? refreshToken : `${tokenType} ${token}`
        }`,
			}
			if (otherOptions.noNeedToken) {
				delete header.Authorization
			}
			const option = {
				isShowLoading: false,
				loadingText: '正在加载',
				url: base + url,
				data: data,
				method: method,
				header,
				success(res) {
					console.log(`${url} \nheader ${JSON.stringify(header)}\nparam ${JSON.stringify(data)}\n`, res)
					if (!otherOptions.noHideLoading) {
						uni.hideLoading()
					}
					if (otherOptions.isLogin) {
						return resolve(res.data)
					}
					permisAuth(url, otherOptions.noCheck).then(()=>{
						if (res.statusCode === HTTP_STATUS.SUCCESS) {
							if (res.data.code === HTTP_STATUS_CODE.AUTHENTICATE) {
								redirectToLogin()
							} else if (res.data.code === HTTP_STATUS.FORBIDDEN) {
								!otherOptions.noToast && showToast(res.data.data || res.data.msg)
								redirectToLogin(HTTP_STATUS.FORBIDDEN)
							} else if (res.data.code === HTTP_STATUS_CODE.SUCCESS) {
								return resolve(res.data)
							} else {
								!otherOptions.noToast && setTimeout(()=>{showToast(res.data.message || res.data.msg)},100)
								reject(res.data.message || res.data.msg)
							}
						} else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
							redirectToLogin()
						} else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
							!otherOptions.noToast && showToast(res.data.data || res.data.msg)
							redirectToLogin(HTTP_STATUS.FORBIDDEN)
						} else {
							!otherOptions.noToast && setTimeout(()=>{showToast(res.data.message || res.data.msg)},100)
							reject(res.data.message || res.data.msg)
							if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
								return logError('api', '请求资源不存在')
							} else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
								return logError('api', '服务端出现了问题')
							} else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
								return logError('api', '没有权限访问')
							}
						}
					}).catch(()=>{})
				},
				error(e) {
					console.log(`请求地址：${url} \n请求体：${JSON.stringify(data)} \n请求失败：${e}`)
					if (!otherOptions.noHideLoading) {
						uni.hideLoading()
					}!otherOptions.noToast && showToast('请求失败')
					reject('请求失败')
					logError('api', '请求接口出现问题', e)
				},
			}
			uni.request(option)
		})
	},
	get(url, data = '', otherOptions, contentType) {
		let option = {
			url,
			data,
			otherOptions,
			contentType
		}
		return this.baseOptions(option)
	},
	post: function(url, data, otherOptions, contentType) {
		console.log("post请求")
		console.log(url)
		let params = {
			url,
			data,
			otherOptions,
			contentType
		}
		return this.baseOptions(params, 'POST')
	},
	put: function(url, data, otherOptions, contentType) {
		let params = {
			url,
			data,
			otherOptions,
			contentType
		}
		return this.baseOptions(params, 'PUT')
	},
	delete: function(url, data, otherOptions, contentType) {
		let params = {
			url,
			data,
			otherOptions,
			contentType
		}
		return this.baseOptions(params, 'DELETE')
	},
	refreshToken: function() {
		this.baseOptions({
				url: '/mci_admin/v1/heal/refresh_token',
				data: {},
				otherOptions: {
					refresh: true
				},
			},
			'PUT'
		).then((res) => {
			const {
				TokenInfo
			} = res.data
			uni.setStorageSync('token', TokenInfo.access_token)
			store.commit('setToken',TokenInfo.access_token)
			uni.setStorageSync(
				'expires_at',
				new Date().getTime() + TokenInfo.expires_at * 1000
			)
			uni.setStorageSync('refreshToken', TokenInfo.refresh_token)
			uni.setStorageSync('tokenType', TokenInfo.token_type)
		})
	},
}